package com.atguigu.tingshu.account.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import com.atguigu.tingshu.account.mapper.RechargeInfoMapper;
import com.atguigu.tingshu.account.mapper.UserAccountDetailMapper;
import com.atguigu.tingshu.account.service.RechargeInfoService;
import com.atguigu.tingshu.account.service.UserAccountService;
import com.atguigu.tingshu.common.constant.SystemConstant;
import com.atguigu.tingshu.common.util.AuthContextHolder;
import com.atguigu.tingshu.model.account.RechargeInfo;
import com.atguigu.tingshu.model.account.UserAccount;
import com.atguigu.tingshu.model.account.UserAccountDetail;
import com.atguigu.tingshu.vo.account.RechargeInfoVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Map;

@Service
@SuppressWarnings({"all"})
public class RechargeInfoServiceImpl extends ServiceImpl<RechargeInfoMapper, RechargeInfo> implements RechargeInfoService {

    @Autowired
    private RechargeInfoMapper rechargeInfoMapper;

    @Autowired
    private UserAccountService userAccountService;

    @Autowired
    private UserAccountDetailMapper userAccountDetailMapper;


    /**
     * 充值-新增充值记录
     *
     * @param rechargeInfoVo
     * @return
     */
    @Override
    public Map<String, String> submitRecharge(RechargeInfoVo rechargeInfoVo) {
        RechargeInfo rechargeInfo = new RechargeInfo();
        rechargeInfo.setUserId(AuthContextHolder.getUserId());
        //为充值记录生成订单编号  确保全局唯一且趋势递增 形式：CZ当天日期+雪花算法
        String orderNo = "CZ" + DateUtil.today().replaceAll("-", "") + IdUtil.getSnowflakeNextId();
        rechargeInfo.setOrderNo(orderNo);
        rechargeInfo.setRechargeStatus(SystemConstant.ORDER_STATUS_UNPAID);
        rechargeInfo.setRechargeAmount(rechargeInfoVo.getAmount());
        rechargeInfo.setPayWay(rechargeInfoVo.getPayWay());
        rechargeInfoMapper.insert(rechargeInfo);

        //TODO 基于RabbitMQ实现自动关闭
        return Map.of("orderNo", orderNo);
    }

    /**
     * 充值-充值成功
     *
     * @param orderNo
     * @return
     */
    @Override
    public void orderPaySuccess(String orderNo) {
        //1. 根据订单编号查询充值记录,获取充值记录，更新充值状态
        RechargeInfo rechargeInfo = rechargeInfoMapper.selectOne(
                new LambdaQueryWrapper<RechargeInfo>()
                        .eq(RechargeInfo::getOrderNo, orderNo)
        );
        rechargeInfo.setRechargeStatus(SystemConstant.ORDER_STATUS_PAID);
        rechargeInfoMapper.updateById(rechargeInfo);
        //2. 充值余额
        boolean flag = userAccountService.update(
                new LambdaUpdateWrapper<UserAccount>()
                        .eq(UserAccount::getUserId, rechargeInfo.getUserId())
                        .setSql("total_amount = total_amount +" + rechargeInfo.getRechargeAmount())
                        .setSql("available_amount = available_amount +" + rechargeInfo.getRechargeAmount())
                        .setSql("total_income_amount = total_income_amount +" + rechargeInfo.getRechargeAmount())
        );
        if (flag) {
            //3.新增账户变动日志
            userAccountService.saveUserAccountDetail(rechargeInfo.getUserId(), "充值",SystemConstant.ACCOUNT_TRADE_TYPE_DEPOSIT, rechargeInfo.getRechargeAmount(), orderNo);
        }


    }

    /**
     * 根据交易类型分页查询账户变动日志
     * @param pageInfo
     * @param tradeType 交易类型：1201-充值 1204-消费
     * @param userId
     * @return
     */
    @Override
    public void getUserAccountDetailPage(Page<UserAccountDetail> pageInfo, String tradeType, Long userId) {
        //1.创建查询条件对象
        LambdaQueryWrapper<UserAccountDetail> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserAccountDetail::getUserId, userId);
        queryWrapper.eq(UserAccountDetail::getTradeType, tradeType);
        queryWrapper.orderByDesc(UserAccountDetail::getCreateTime);
        //2.执行分页条件查询
        userAccountDetailMapper.selectPage(pageInfo, queryWrapper);
    }
}
